
const userinfo = {};
const col = "user_info";

/**
 * @description: 存储方法
 * @param {object} context 方法对象
 * @param {object} obj 存储的数据
 * @return {object} 结果
 */
userinfo.insert = async (context, obj)=>{
  try{
    let resData;
    //  查询当前用户是否存在
    let isExist = await context.mfutil.db.mongo.count( col, {
      mix_userid: obj.mix_userid
    } );

    if(isExist){
      // 更新用户访问次数
      resData = await context.mfutil.db.mongo.updateMany( col, {
        mix_userid: obj.mix_userid
      }, {$set: obj, $inc: { accessCount: 1 }});
    }else{
      // 用户数据写入 访问次数写入
      resData = await context.mfutil.db.mongo.insertOne(col, {...obj, accessCount: 1});
    }
    return {
      success: true,
      data: resData,
      errorCode: "",
      errorMessage: ""
    }
  }catch(e){
    return {
      success: false,
      data: {},
      errorCode: "999",
      errorMessage: JSON.stringify(e)
    }
  }
}

/**
 * @description: 查询方法
 * @param {object} context 方法对象
 * @param {object} filter 查询条件
 * @return {object} 结果
 */
userinfo.get = async(context, filter) =>{
  try{
    let infores = await context.mfutil.db.mongo.find(col, filter);
    return {
      success: true,
      data: infores,
      errorCode: "",
      errorMessage: ""
    }
  }catch(e){
    return {
      success: false,
      data: {},
      errorCode: "999",
      errorMessage: JSON.stringify(e)
    }
  }
}


/**
 * @description: 新增key方法
 * @param {object} context 方法对象
 * @param {object} obj 入参
 * @return {object} 新增key结果
 */
userinfo.insertKey = async(context, obj) =>{
  try{
    let infores = await context.mfutil.db.mongo.updateMany( col, {mix_userid: obj.mix_userid}, {$set: obj});
    return {
      success: true,
      data: infores,
      errorCode: "",
      errorMessage: ""
    }
  }catch(e){
    return {
      success: false,
      data: {},
      errorCode: "999",
      errorMessage: JSON.stringify(e)
    }
  }
}

/**
 * @description: 原子计数方法
 * @param {object} context 方法对象
 * @param {object} obj 数据
 * @return {object} 结果
 */
userinfo.incrKey = async(context, col, obj) => {
  try{
    let infores = await context.mfutil.db.mongo.updateMany(col, obj);
    return {
      success: true,
      data: {
        res: infores
      },
      errorCode: "",
      errorMessage: ""
    }
  }catch(e){
    return {
      success: false,
      data: {},
      errorCode: "999",
      errorMessage: JSON.stringify(e)
    }
  }
}


module.exports = exports.userinfo = userinfo;;